package com.xbongbong.crm.service.permission;

import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.parent.abstracts.AbstractBusinessPermissionService;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.permission.pojo.dto.VerifyViewPermissionDTO;
import com.xbongbong.pro.statistic.result.pojo.ElasticAggsPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.subform.SubFormTransferEnum;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.sys.util.UserPermissionUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import static com.xbongbong.paas.enums.IndexTypeEnum.IDX_SAAS_CONTACT_TEAM;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author sunshaoxiang
 * @ClassName ContactPermissionServiceImpl
 * @Description 联系人权限 Service
 * @Date 2022/6/23 10:43
 * @Version 1.0
 **/
@Service
public class ContactPermissionServiceImpl extends AbstractBusinessPermissionService<PaasFormDataEntityExt, PaasFormEntityExt> {

    @Resource
    private UserModel userModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private EsHelper esHelper;

    @Override
    public List<Integer> businessType() {
        return Collections.singletonList(XbbRefTypeEnum.CONTACT.getCode());
    }

    @Override
    public Boolean checkPermissionByTeam(String corpid, Integer businessType, BoolQueryBuilder boolQueryBuilder) throws XbbException {
        return null;
    }

    @Override
    public void checkPermission(PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, UserVO loginUser, Integer subBusinessType) throws XbbException {
        VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO(loginUser, paasFormDataEntityExt);
        //没有团队权限且没有共享抛异常
        boolean hasDataPermission = hasPermission(formEntity, paasFormDataEntityExt, loginUser, subBusinessType)
                || sharePermissionHelp.verifySharePermission4QueryWithRuleEngine(verifyViewPermissionDTO);
        if (!hasDataPermission) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
        }
    }

    @Override
    public boolean hasPermission(PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, UserVO loginUser, Integer subBusinessType) throws XbbException {
        if (UserPermissionUtil.isMaxDataPermission(loginUser, formEntity.getSaasMark(), formEntity.getBusinessType(), formEntity.getDistributorMark(), formEntity.getMenuId(), false)){
            return true;
        }
        Long dataId = paasFormDataEntityExt.getId();
        Integer dataPermission = userModel.getDataPermission(loginUser, false);
        List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, loginUser.getUserId(), loginUser.getCorpid(), BasicConstant.ZERO,false);
        String corpid = formEntity.getCorpid();
        Long customerId = paasFormDataEntityExt.getData().getLong(ContactEnum.CUSTOMER_NAME.getAttr());
        if (Objects.nonNull(customerId)) {
            CustomerEntityExt customerEntityExt = customerModel.getByKey(customerId, paasFormDataEntityExt.getCorpid());
            if (Objects.nonNull(customerEntityExt) && Objects.equals(customerEntityExt.getDel(), DelEnum.NORMAL.getDel())) {
                Integer isPublic = customerEntityExt.getData().getInteger(CustomerManagementEnum.IS_PUBLIC.getAttr());
                if (Objects.equals(isPublic, 1)) {
                    // 联系人，如果他关联的客户是公海客户，那么就不校验团队
                    return true;
                }
            }
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(IDX_SAAS_CONTACT_TEAM, FieldTypeEnum.DATAID.getAlias()), dataId));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(IDX_SAAS_CONTACT_TEAM, ParameterConstant.USER_ID), userIdIn));
        ElasticAggsPojo elasticAggsPojo = esHelper.elasticAggs(IDX_SAAS_CONTACT_TEAM, boolQueryBuilder, null);
        boolean hasPermission =  StringUtil.toInt(elasticAggsPojo.getTotal(), 0) > 0;
        return hasPermission;
    }
}
